﻿using B.S.Base.Write.API.Application.Command;
using MediatR;
using System.Security;
using System.Security.Cryptography;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture.Infasetures;

namespace B.S.Base.Write.API.Application.CommandHandLer
{
    public class AddMenutRoleCommandHandLer : IRequestHandler<AddMenutRoleCommand, APIResult<object>>
    {
        private readonly IBaseRepostiy<MenuRoleModel> _menuRoleModel;

        public AddMenutRoleCommandHandLer(IBaseRepostiy<MenuRoleModel> _menuRoleModel)
        {
            this._menuRoleModel = _menuRoleModel;
        }
        public async Task<APIResult<object>> Handle(AddMenutRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>
            {
                Code = ResultCode.Ok,
                Message = "成功"
            };

            // 先查出所有要删除的
            var toDelete = _menuRoleModel.GetAll().Where(x => x.Rid == request.Rid).ToList();
            foreach (var entity in toDelete)
            {
                await Task.Run(() => _menuRoleModel.Delete(entity));
            }

            var mids = request.Mid.Split(',').ToList();
            foreach (var mid in mids)
            {
                if (int.TryParse(mid, out int midValue) && midValue != 0)
                {
                    var entity = new MenuRoleModel()
                    {
                        Rid = request.Rid,
                        Mid = midValue
                    };
                    await _menuRoleModel.AddAsync(entity);
                }
            }

            return result;
        }
    }
}
